﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Shell;
using Tulde.WindowsPhone.Music.Mp3Tunes;
using Tulde.WindowsPhone.Music.ViewModel;
using System.Linq;

namespace Tulde.WindowsPhone.Music
{
    /// <summary>
    /// Updates the Shell Tilte Icon For This Application
    /// </summary>
    public class ShellTileUpdateService
    {
        private ShellTileSchedule mySchedule;

        public ShellTileUpdateService( )
        {
    
     
           
            

        }
        /// <summary>
        /// Using the Locker API, gets the most recently played track and downloads it's corresponding album art.
        /// This method can be disabled through application settings.
        /// </summary>
        public void GetLatestAlbumArt()
        {
            if (SettingsProvider.Settings.EnablePNS)
            {
                this.mySchedule = this.mySchedule?? new ShellTileSchedule();
                LockerDataService<TrackCollection> dataService = new LockerDataService<TrackCollection>();
                Uri uri = dataService.CreateServiceEndpoint(LockerDataOperations.lockerStats,
                    new LockerStatParameters
                    {

                        PartnerToken = SecurityProvider.Credentials.Domain,
                        User = SecurityProvider.Credentials.UserName,
                        Count = "1"
                    }
                   );
                dataService.InvokeAsynch<TrackCollection>(uri, tracks =>
                {

                    if (tracks.Tracks != null && tracks.Tracks.Any())
                    {
                        var item = tracks.Tracks.FirstOrDefault();
                        AlbumArtService service = new AlbumArtService();
                        Uri url = service.CreateServiceEndpoint(LockerDataOperations.albumartget, new AlbumArtServiceParameters
                        {
                            AlbumServiceKey = item.AlbumId,
                            Size = AlbumArtSizeOptions.large
                        });
                        this.mySchedule.Interval = UpdateInterval.EveryHour;

                        this.mySchedule.Recurrence = UpdateRecurrence.Interval;
                        this.mySchedule.StartTime = DateTime.Now;
                        this.mySchedule.RemoteImageUri = url;
                        this.mySchedule.Start();
                    }

                });
            }
        }
    }
}
